package com.ahcloud.enhance.curator.configuration;

import com.ahcloud.enhance.curator.exception.UnknownRetryPolicyException;
import com.ahcloud.enhance.curator.utils.ReflectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.retry.BoundedExponentialBackoffRetry;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryForever;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.retry.RetryUntilElapsed;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UnknownFormatFlagsException;

/**
 * @program: distributedlock-enhance
 * @description:
 * @author: YuKai Fan
 * @create: 2024/4/30 23:54
 **/
public class RetryPolicyFactory {

    public static RetryPolicy getPolicyByName(CuratorProperties.RetryPolicyConfig config) {
        String policyName = config.getPolicyName();
        if (StringUtils.isBlank(policyName)) {
            // 默认为 每隔3秒， 重试3次，
            return new RetryNTimes(3, 3000);
        }
        switch (policyName) {
            case "RetryNTimes":
                return new RetryNTimes(config.getMaxRetries(), config.getRetryIntervalMs());
            case "RetryOneTime":
                return new RetryOneTime(config.getRetryIntervalMs());
            case "BoundedExponentialBackoffRetry":
                return new BoundedExponentialBackoffRetry(config.getBaseSleepTimeMs(), config.getRetryIntervalMs(), config.getMaxRetries());
            case "ExponentialBackoffRetry":
                return new ExponentialBackoffRetry(config.getBaseSleepTimeMs(), config.getMaxRetries());
            case "RetryForever":
                return new RetryForever(config.getRetryIntervalMs());
            case "RetryUntilElapsed":
                return new RetryUntilElapsed(config.getMaxElapsedTimeMs(), config.getRetryIntervalMs());
            default:
                throw new UnknownRetryPolicyException(policyName);
           }
    }
}
